package org.huzhp.data.handler;

import cn.hutool.db.DbUtil;
import org.huzhp.data.core.DbInfo;
import org.huzhp.data.exception.DataException;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @Description: 数据操作抽象类
 * @Author: huzp
 * @CreateDate: 2020/4/22 10:24
 * @Version: 1.0
 */
public abstract class AbstractHandler implements IHandler {

    protected DataSource buildDataSource(DbInfo db){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(db.getJdbcUrl());
        dataSource.setUsername(db.getUsername());
        dataSource.setPassword(db.getPassword());
        return dataSource;
    }


    @Override
    public boolean testDB(DbInfo dbInfo) throws DataException {
        Connection connection = null;
        try {
            connection = connect(buildDataSource(dbInfo));
        } catch (DataException e) {
            return false;
        }finally {
            DbUtil.close(connection);
        }
        return true;
    }

    public abstract Connection connect(DataSource dataSource);

    @Override
    public boolean bakDB(DbInfo db, String table, String path) throws DataException {
//        if (table)
        return false;
    }
}
